var dao = require('./messenger.dao.js');
var user = require('./user/user.js');

var count = 0;

var createRoom = function() {
	// TODO: return random number
	return count++;
};

/*
 * Export functions
 */
exports.initialize = function(io, socket) {
	console.log('initialize messenger module...');
	
	socket.on('login', function(credential) {
		user.login(credential, function(result) {
			// return login result as boolean type
			socket.emit('login', result);
			
			if (result) {
				// create user room to make it easier to find user's socket
				socket.join(credential.username);
				socket.set('name', credential.username);
			}
		});
	});
	
	socket.on('buddies', function() {
		socket.get('name', function(error, name) {
			console.log('get buddies of ' + name + '...');
			user.getBuddies(name, function(rows) {
				console.log(rows);
				socket.emit('buddies', rows);
			});
		});
	});
	
	socket.on('history', function(to) {
		socket.get('name', function(error, name) {
			console.log('get history of ' + name + '...');
			dao.getHistory(name, to, function(rows) {
				rows.forEach(function(row) {
					console.log(row.from + ': ' + row.message);
				});
				
				// update unread to zero because all of unread histories will be retrieved
				user.setUnread(name, to, 0);
				
				socket.emit('history', {
					to: to,
					rows: rows,
					unread: 0
				});
			});
		});
	});

	socket.on('message', function(data) {
		console.log('message arrived: ' + data.message);
		
		socket.get('name', function(error, name) {
			// write message into data store
			dao.write(data.id, name, data.to, data.message);
			
			data.from = name;
			
			// increase unread count
			user.increaseUnread(data.to, name);
			user.getUnread(data.to, name, function(rows) {
				data.unread = rows[0].unread;
				
				console.log('emit message:: ' + JSON.stringify(data));
				io.sockets['in'](data.to).emit('message', data);	
			});
			
			socket.emit('message', data);
		});
	});
	
	socket.on('read', function(data) {
		socket.get('name', function(error, name) {
			dao.find({id: data.id}, null, null, function(messages) {
				console.log('read event on: ' + data.id);
				
				if (!messages[0].read) {
					messages[0].read = true;
					messages[0].save();	
				}				
			});
			
			user.decreaseUnread(name, data.friend);
		});
	});
};